package com.yun.zf.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yun.zf.common.admin.domain.SysRole;
import com.yun.zf.common.admin.domain.SysRoleDept;
import com.yun.zf.common.admin.domain.SysRoleMenu;
import com.yun.zf.common.admin.dto.sys.RoleListDto;
import com.yun.zf.common.admin.model.sys.RoleAddMo;
import com.yun.zf.common.admin.model.sys.RoleSearchMo;
import com.yun.zf.common.constant.UserConstants;
import com.yun.zf.common.utils.StringUtils;
import com.yun.zf.system.exception.CustomException;
import com.yun.zf.system.mapper.SysRoleMapper;
import com.yun.zf.system.mapper.SysRoleMenuMapper;
import com.yun.zf.system.mapper.SysUserRoleMapper;
import com.yun.zf.system.service.ISysMenuService;
import com.yun.zf.system.service.ISysRoleMenuService;
import com.yun.zf.system.service.ISysRoleService;
import com.yun.zf.system.service.SysRoleDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 角色 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysRoleDeptService roleDeptService;
    @Autowired
    private ISysRoleMenuService roleMenuService;
    @Autowired
    private ISysMenuService menuService;


    /**
     * 根据条件分页查询角色数据
     *
     * @param role 角色信息
     * @return 角色数据集合信息
     */
    @Override
    public IPage<SysRole> selectRoleList(RoleSearchMo role) {
        QueryWrapper<SysRole> roleQueryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper lambdaQueryWrapper = roleQueryWrapper.lambda().eq(StringUtils.isNotEmpty(role.getRoleName()), SysRole::getRoleName, role.getRoleName())
                .eq(StringUtils.isNotEmpty(role.getRoleKey()), SysRole::getRoleKey, role.getRoleKey())
                .eq(SysRole::getDelFlag, "0")
                .eq(!("all".equals(role.getStatus())), SysRole::getStatus, role.getStatus());

        Page<SysRole> page = new Page<>(role.getCurrent(), role.getPageSize());
        IPage<SysRole> rolePage =roleMapper.selectPage(page,lambdaQueryWrapper);
        return rolePage;
    }


    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectRolePermissionByUserId(Long userId) {
        List<SysRole> perms = roleMapper.selectRolePermissionByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (SysRole perm : perms) {
            if (StringUtils.isNotNull(perm)) {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }


    /**
     * 通过角色ID查询角色
     *
     * @param roleId 角色ID
     * @return 角色对象信息
     */
    public SysRole selectRoleById(Long roleId) {
        QueryWrapper<SysRole> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.lambda().eq(SysRole::getRoleId, roleId);
        SysRole role = baseMapper.selectOne(roleQueryWrapper);
        List<Object> menuList = roleMenuService.getMenuIds(role.getRoleId());
        String[] ids = new String[menuList.size()];
        for (int i = 0; i < menuList.size(); i++) {
            ids[i] = String.valueOf(menuList.get(i));
        }
        role.setMenuIds(ids);
        return role;
    }

    /**
     * 校验角色名称是否唯一
     *
     * @param
     * @return 结果
     */
    @Override
    public String checkRoleNameUnique(Long roleId, String roleName) {
        QueryWrapper<SysRole> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.lambda().eq(SysRole::getRoleName, roleName);
        List<SysRole> roleList = baseMapper.selectList(roleQueryWrapper);
        if (roleList.size() > 0 && !roleList.get(0).getRoleId().equals(roleId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色权限是否唯一
     *
     * @param
     * @return 结果
     */
    @Override
    public String checkRoleKeyUnique(Long roleId, String roleKey) {
        QueryWrapper<SysRole> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.lambda().eq(SysRole::getRoleKey, roleKey);
        List<SysRole> roleList = baseMapper.selectList(roleQueryWrapper);
        if (roleList.size() > 0 && !roleList.get(0).getRoleId().equals(roleId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色是否允许操作
     *
     * @param
     */
    public void checkRoleAllowed(Long roleId) {
        SysRole role = new SysRole(roleId);
        // 获取登录人是否为管理员，如果为管理员可对管理员数据进行修改
        if (StringUtils.isNotNull(role.getRoleId()) && role.isAdmin()) {
            throw new CustomException("不允许操作超级管理员角色");
        }

    }

    /**
     * 通过角色ID查询角色使用数量
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public int countUserRoleByRoleId(Long roleId) {
        return userRoleMapper.countUserRoleByRoleId(roleId);
    }

    /**
     * 新增保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public boolean insertRole(RoleAddMo role) {
        // 新增角色信息
        roleMapper.insertRole(role);
        return insertRoleMenu(role);
    }

    /**
     * 修改保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public boolean updateRole(RoleAddMo role) {
        // 修改角色信息
        roleMapper.updateRole(role);
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());
        return insertRoleMenu(role);
    }

    /**
     * 修改角色状态
     *
     * @param
     * @return 结果
     */
    public int updateRoleStatus(Long roleId, String status) {
        return roleMapper.updateRoleStatus(roleId, status);
    }

    /**
     * 修改数据权限信息
     *
     * @param
     * @return 结果
     */
    @Override
    @Transactional
    public Boolean authDataScope(Long roleId, String dataScope, Long[] deptIds) {
        // 修改角色信息
        roleMapper.updateRoleScope(roleId, dataScope);
        // 删除角色与部门关联
        roleDeptService.deleteRoleDeptByRoleId(roleId);
        // 新增角色和部门信息（数据权限）
        if (deptIds.length == 0) {
            return true;
        }
        return insertRoleDept(roleId, deptIds);
    }

    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     */
    public boolean insertRoleMenu(RoleAddMo role) {
        boolean flage = false;
        // 新增用户与角色管理
        List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
        if (role.getMenuIds() != null && role.getMenuIds().length > 0) {
            for (String menuId : role.getMenuIds()) {
                SysRoleMenu rm = new SysRoleMenu();
                rm.setRoleId(role.getRoleId());
                rm.setMenuId(Long.parseLong(menuId));
                list.add(rm);
            }
        }

        if (list.size() > 0) {
            flage = roleMenuService.saveBatch(list);
        }
        return flage;
    }

    /**
     * 新增角色部门信息(数据权限)
     *
     * @param
     */
    public Boolean insertRoleDept(Long roleId, Long[] deptIds) {
        // 新增角色与部门（数据权限）管理
        List<SysRoleDept> list = new ArrayList<SysRoleDept>();
        for (Long deptId : deptIds) {
            SysRoleDept rd = new SysRoleDept();
            rd.setRoleId(roleId);
            rd.setDeptId(deptId);
            list.add(rd);
        }
        if (list.size() > 0) {
            return roleDeptService.batchRoleDept(list);
        }
        return false;
    }

    /**
     * 通过角色ID删除角色
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public int deleteRoleById(Long roleId) {
        return roleMapper.deleteRoleById(roleId);
    }

    /**
     * 批量删除角色信息
     *
     * @param roleIds 需要删除的角色ID
     * @return 结果
     */
    public void deleteRoleByIds(Long[] roleIds) {
        for (Long roleId : roleIds) {
            checkRoleAllowed(roleId);
            SysRole role = selectRoleById(roleId);
            if (countUserRoleByRoleId(roleId) > 0) {
                throw new CustomException(String.format("%1$s已分配,不能删除", role.getRoleName()));
            }
        }
        roleMapper.deleteRoleByIds(roleIds);
    }

    @Override
    public List<SysRole> getRoles(Long userId) {
        return roleMapper.getRoles(userId);
    }

    @Override
    public List<RoleListDto> getAllRoles() {
        return baseMapper.getInAgentRole();
    }

    /**
     * 验证角色是否已经删除
     * @param roleId
     * @return
     */
    @Override
    public int checkDelFlag(Long roleId) {
        QueryWrapper<SysRole> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.lambda().eq(SysRole::getDelFlag,0).eq(SysRole::getRoleId, roleId);
        return baseMapper.selectCount(roleQueryWrapper);
    }
}

